<template>
  <div>
    <!-- <van-nav-bar title="审批单详情" left-text="返回" left-arrow @click-left="onClickLeft" /> -->
    <van-nav-bar
      :title="lcsubmit!=='lcsubmit'?'审批单详情':'大交通信息详情'"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="van_card">
      <div class="van_card_title eventnumber">会议编号：{{eventid}}</div>
      <van-row>
        <van-col class="van_card_title" span="24">基本信息</van-col>
        <van-col class="individual_info" span="24">
          <p>申请人：{{individualInfo.bookname}}</p>
          <p>HCP姓名：{{individualInfo.paxname}}</p>
          <p
            v-if="individualInfo.staffno&&individualInfo.staffno.indexOf('__')==-1"
          >UCI CODE：{{individualInfo.staffno}}</p>
          <p>医院：{{trdetail.HCPHospital ||trdetail.hospital}}</p>
        </van-col>
      </van-row>
    </div>
    <div class="van_card">
      <div class="van_card_title">交通信息</div>
      <div
        v-for="(item,index) in individualInfo.trips"
        :key="index"
        class="journey_list van-hairline--bottom"
      >
        <div class="journey_list_title">
          <span v-if="!item.originalexno">第{{index+1}}程</span>
          <span class="journey_list_title_change" v-else-if="item.tripstatus.indexOf('退票')!==-1">退票</span>

          <span v-else class="journey_list_title_change">改期</span>
          <span class="flight_no">
            <img
              v-if="item.triptype!='T'"
              :src="'https://ezway.efasco.com/wxapp/img/'+item.flightno.substr(0,2)+'.png'"
            />
            {{item.flightno}}
          </span>
        </div>
        <van-row gutter="20">
          <van-col class="procedule_column procedule_column_left" span="8">
            <div class="date_start">
              <p>{{item.depdate}}</p>
              <p>{{item.deptime}}</p>
            </div>
            <div class="date_end">
              <p>{{item.arrdate}}</p>
              <p>{{item.arrtime}}</p>
            </div>
          </van-col>
          <van-col class="procedule_column procedule_column_right" span="8">
            <div class="date_start">
              <p>{{item.depairpot}}{{item.deptem}}</p>
            </div>
            <div class="date_duration">
              <p>{{new Date(item.arrdate.replace(/-/g, "/")+" "+item.arrtime.replace(/-/g, "/"))-new Date(item.depdate.replace(/-/g, "/")+" "+item.deptime.replace(/-/g, "/")) | duration}}</p>
            </div>
            <div class="date_end">
              <p>{{item.arrairpot}}{{item.arrtem}}</p>
            </div>
          </van-col>
        </van-row>
        <div class="journey_list_context">
          <p>订单状态：{{item.tripstatus}}</p>
          <p>{{lcsubmit=='lcsubmit'?'最晚出票时限：':'最晚审批时限：'}}{{item.freecanceldeadline}}</p>
          <p>舱位：{{item.cabinlevel}}</p>
          <p
            v-if="item.rccode||item.rcremark"
          >原因代码：{{pd_if_null(item.rccode||item.rcremark) +' '+((item.dtRcRemark&&item.dtRcRemark!=null&&item.dtRcRemark.split('/')[0])||item.rccode||'') }}</p>
          <p
            v-if="!((item.lowestprice*1!=0&&item.lowestprice==(item.price*1+item.tax*1))||item.routetype!='D'||item.lowestprice*1==0||item.rccode=='null'||!item.lowestinfo)"
          >最低参考票价：(¥{{item.lowestprice}}){{item.lowestinfo}}</p>
          
          <p>
            价格：
            <span
              class="total_p"
            >¥ {{(item.routetype=='D'?(item.price*1+item.tax*1):item.price*1)}}</span>
          </p>
          <div v-if="Status=='退票'&&item.tripstatus=='已出票'" style="text-align: end;">
            <van-button @click="refund_(item,index)" type="info" size="mini">申请退票</van-button>
          </div>
        </div>
      </div>
    </div>
    <div class="van_card">
      <div class="van_card_title">总计</div>
      <div class="total_fare">
        <p>
          总费用：
          <span class="total_p">¥ {{totalprice}}</span>
        </p>
        <p>审批时限：{{deadline}}</p>
      </div>

      <div v-if="Status==='已提交审批'&&lcsubmit!=='lcsubmit'" class="block"></div>
    </div>
    <div v-if="Status==='已提交审批'&&lcsubmit!=='lcsubmit'" class="approval_fixed_btn">
      <van-button plain type="info" @click="ApproveRocheTR(false)">拒绝审批</van-button>
      <van-button type="info" @click="ApproveRocheTR(true)">通过审批</van-button>
    </div>

    <van-dialog
      v-model="refoundDialog"
      title="确认退票"
      show-cancel-button
      close-on-click-overlay
      :before-close="beforeClose"
    >
      <p class="refond_info">退票可能会产生退票费，具体费用以航司/铁路12306最终结果为准</p>
      <van-field v-model="refoundReason" name="退票理由" placeholder="请输入退票理由" />

      <p v-if="refoundTips" class="refond_error">请输入退票理由</p>
    </van-dialog>
  </div>
</template>

<script>
import apilist from "../utils/apiList";
export default {
  data() {
    return {
      eventid: "",
      orderst: "待审批",
      individualInfo: {},
      all_C: [],
      trdetail: null,
      PaxStaffNo: "",
      lcsubmit: "",
      Status: "",
      // 退票功能
      refoundDialog: false,
      refoundReason: "",
      refoundTips: false,
      nc: [],
      event: {},
    };
  },
  created() {
    this.eventid = this.$route.query.eventid;
    this.PaxStaffNo = this.$route.query.PaxStaffNo;
    this.lcsubmit = this.$route.query.lcsubmit;
    this.Status = this.$route.query.Status;
    this.trdetail = JSON.parse(sessionStorage.getItem("trdetail"));
    this.getcurrentStaffInfo();
  },
  computed: {
    totalprice: function () {
      var p = this.individualInfo.trips || [];
      var a = 0;
      p.map(function (v, i) {
        a += v.routetype == "D" ? v.price * 1 + v.tax * 1 : v.price * 1;
      });
      return a;
    },
    deadline: function () {
      var au_dl = "";
      if (
        !!this.individualInfo &&
        !!this.individualInfo.trips &&
        this.individualInfo.trips.length > 0
      ) {
        for (var i = 0; i < this.individualInfo.trips.length; i++) {
          var t = this.individualInfo.trips[i];
          if (t.freecanceldeadline) {
            var tf = new Date(
              t.freecanceldeadline.replace(/-/g, "/")
            ).getTime();
            if (!au_dl) au_dl = tf;
            if (tf < au_dl) au_dl = tf;
          }
        }
      }
      if (
        !!this.individualInfo &&
        !!this.individualInfo.hotels &&
        this.individualInfo.hotels.length > 0
      ) {
        for (var i = 0; i < this.individualInfo.hotels.length; i++) {
          var t = this.individualInfo.hotels[i];
          if (t && t.freecanceldeadline) {
            var tf = new Date(
              t.freecanceldeadline.replace(/-/g, "/")
            ).getTime();
            if (!au_dl) au_dl = tf;
            if (tf < au_dl) au_dl = tf;
          }
        }
      }
      if (au_dl) return new Date(au_dl).format("yyyy-MM-dd hh:mm");
      return new Date().format("yyyy-MM-dd hh:mm");
    },
  },
  methods: {
    // 确认退票

    refund_: function (o, i) {
      this.refoundDialog = true;
      this.nc[0] = o;
      this.nc[1] = i;
    },
    beforeClose(action, done) {
      if (action === "confirm") {
        if (!this.refoundReason) {
          this.refoundTips = true;
          done(false);
        } else {
          this.refoundTips = false;
          this.$axios
            .get(
              "https://ezway.efasco.com/ErpService.asmx/RefundExorder?ex_no=" +
                this.nc[0].ex_no
            )
            .then((res) => {
              this.loading = false;
              if (res.data == "success") {
                this.$notify({
                  message:
                    "您的退票申请已提交，如有问题，旅行顾问将及时与您联系",
                  type: "success",
                  duration: 1000,
                });
                window.location.reload();
              } else {
                this.$notify({
                  message: "退票失败",
                  type: "danger",
                  duration: 1000,
                });
              }
            })
            .catch(function (error) {
              this.$notify({
                message: "退票失败",
                type: "danger",
                duration: 1000,
              });
            });

          done();
        }
      } else {
        done();
      }
    },
    // 获取当前人员会议详情
    async getcurrentStaffInfo() {
      const res = await this.$axios.get(
        apilist[1] +
          "/GetRocheTripsByEventid?staffno=" +
          this.PaxStaffNo +
          "&eventid=" +
          this.eventid
      );
      res.data.list[0].trips = res.data.list[0].trips.filter((v, i) => {
        return v.eorderno == this.trdetail.No || this.trdetail.trips;
      });
      console.log(res.data.list[0].trips);
      res.data.list[0].trips.sort(function (a, b) {
        // return a.ex_no.split('-')[1]-b.ex_no.split('-')[1];
        if (a.originalexno && b.originalexno) {
          return a.ex_no.split("-")[1] - b.ex_no.split("-")[1];
        } else if (!a.originalexno && !b.originalexno) {
          return a.ex_no.split("-")[1] - b.ex_no.split("-")[1];
        } else {
          if (!a.originalexno) {
            return -1;
          } else {
            return 1;
          }
        }
      });
      let g = res.data.list[0];
      g.trips.map(function (v, i) {
        v.status = "";
        if (v.tripstatus == "已取消" || v.tripstatus == "审批不通过") {
          v.price = 0;
          v.tax = 0;
        }
        if (v.tripstatus === "已取消") v.tripstatus = "取消审批";

        if (v.tripstatus == "重复出票") {
          v.tripstatus = "重复出票，预定已取消";
        }
        if (!v.status && v.ticketno) v.status = "已出票";
        if (v.originalexno) {
          v.status = "已出票";
          g.trips.map(function (v2, i2) {
            if (v2.ex_no == v.originalexno) {
              v2.status = "被改期";
            }
          });
        }
      });
      this.orderst = this.individualInfo.status;
      if (!this.orderst) this.orderst = "待审批";
      this.individualInfo = g;
      this.event = JSON.parse(sessionStorage.getItem("event"));
    },
    // 审批功能
    getcost: function (eventid, fn) {
      this.$axios
        .get(apilist[1] + "/GetRocheEventFee?eventid=" + eventid)
        .then(function (res) {
          if (fn) {
            fn(res.data);
          }
        })
        .catch(function (e) {});
    },
    ApproveRocheTR: function (x) {
      let _this = this;
      let p = this.individualInfo.trips;
      _this.all_C = [];
      if (x) {
        var budget = _this.event.EventBudgetList[0].BudgetAmount;
        _this.getcost(_this.event.IDNo, function (cost) {
          p.map(function (z, o) {
            cost += z.routetype == "D" ? z.price * 1 + z.tax * 1 : v.price * 1;
          });
          console.log(cost);
          if (cost > budget) {
            _this.$notify({
              type: "warning",
              message: "当前会议的大交通使用额度已超过预算，请尽快更新预算",
            });
            return;
          } else {
            _this.ApproveRocheTR0(x, p);
          }
        });
      } else {
        _this.ApproveRocheTR0(x, p);
      }
      return;
    },
    ApproveRocheTR0: function (x, p) {
      var _this = this;
      var load_st = false;
      p.map(function (v, i) {
        var fnx = x ? _this.ApproveRocheTR2 : _this.ApproveRocheTR3;
        fnx(v, i, function () {
          var alls = true;
          var all_false = true;
          _this.all_C.map(function (vv, ii) {
            if (!vv) alls = false;
            if (vv != "false") all_false = false;
          });
          if (alls && !load_st) {
            load_st = true;
            if (all_false) {
              _this.$notify({ type: "danger", message: "提交失败" });
              return;
            }
            _this.$notify({ type: "success", message: "提交成功" });
            _this.$router.go(-1);
          }
        });
      });
    },
    ApproveRocheTR2: function (v, i, fn) {
      var _this = this;
      this.$axios
        .get(apilist[1] + "/ApproveRocheTR?ex_no=" + v.ex_no)
        .then(function (res) {
          _this.all_C[i] = true;
          // console.log(res);
          if (res.data && fn) {
            fn();
          }
        })
        .catch(function (error) {
          _this.all_C[i] = "false";
        });
    },
    ApproveRocheTR3: function (v, i, fn) {
      var _this = this;
      this.$axios
        .get(apilist[1] + "/UnApproveExorder?exno=" + v.ex_no)
        .then(function (res) {
          _this.all_C[i] = true;
          // console.log(res);
          if (res.data && fn) {
            fn();
          }
        })
        .catch(function (error) {
          _this.all_C[i] = "false";
        });
    },
    pd_if_null: function (a) {
      return a && a != "null" ? a : "";
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
  filters: {
    duration: function (dur) {
      const h = Math.floor(dur / 1000 / 3600);
      const min = (dur / 1000 / 60) % 60;
      return `${h}H${min}M`;
    },
  },
};
</script>

<style lang="less" scoped>
.individual_info p {
  color: #666666;
  line-height: 26px;
}
.total_fare {
  p {
    font-weight: 600;
    color: #333333;
  }
}
.total_p {
  color: #ff7600;
}
.refond_error {
  padding: 0 16px;
  font-size: 12px;
  color: #ee0a24;
}
.refond_info {
  padding: 0 16px;
  font-size: 12px;
  color: #333333;
}
.journey_list {
  .journey_list_title {
    span {
      font-size: 12px;
      display: inline-block;
      color: #fff;
      width: 56px;
      height: 19px;
      line-height: 19px;
      text-align: center;
      background: #2d8cf0;
      border-radius: 74px 73px 74px 0px;
      margin: 10px 0;
    }
    .flight_no {
      background: #fff;
      color: #666666;
      width: 100px;
      text-align: left;
      margin-left: 5px;
      img {
        width: 16px;
        height: 16px;
        position: relative;
        top: 2px;
      }
    }
    .journey_list_title_change {
      background-color: #ff7600;
    }
  }

  .journey_list_context {
    padding: 10px 0;
  }

  .procedule_column {
    height: 100px;
    position: relative;
    font-size: 14px;
    display: flex;
    flex-flow: column;
    justify-content: space-between;

    .date_start,
    .date_end,
    .date_duration {
      p {
        margin: 0;
        line-height: 16px;
      }
    }
  }
  .procedule_column_right {
    margin-left: 20px;
  }
  .procedule_column_left {
    border-right: 1px dotted #2d8cf0;
    &::after {
      content: "";
      width: 10px;
      color: #2d8cf0;
      height: 10px;
      position: absolute;
      top: 0;
      right: -6px;
      background-color: #2d8cf0;
      border-radius: 50%;
    }
    &::before {
      content: "";
      width: 10px;
      color: #2d8cf0;
      height: 10px;
      position: absolute;
      bottom: 0;
      right: -6px;
      background-color: #2d8cf0;
      border-radius: 50%;
    }
  }
}
</style>